<?php

namespace app\common\model;

use org\util\TreeUtil;
use think\Validate;
class UserModel extends BaseModel
{
    protected $name = 'user'; //定义用户表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = true;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改
    //类型自动转换
    protected $type = [];

    //设置用户密码
    protected function setPasswordAttr($value)
    {
        return md5(sha1($value));
    }

    /**
     * 添加用户
     * @param $data
     * @return bool
     */
    public function addData($data)
    {
        try{
            if (empty($data['username']) && empty($data['mobile']) && empty($data['email'])) {
                exception('用户名/手机号/邮箱至少应该填写一个',40001);
            }
            if (!empty($data['username'])) {
                if ($this->isUserName($data['username']) === false) {
                    exception('用户名格式错误',40001);
                }
                if ($this->where('username', $data['username'])->find()) {
                    exception('该用户已存在',40001);
                }
            }
            if (!empty($data['mobile'])) {
                if ($this->isMobile($data['mobile']) === false) {
                    exception('手机号格式不正确',40001);
                }
                if ($this->where('mobile', $data['mobile'])->find()) {
                    exception('该手机号已注册',40001);
                }
            }
            if (!empty($data['email'])) {
                if($this->isEmail($data['email'])===false){
                    exception('email格式不正确',40001);
                }
                if ($this->where('email', $data['email'])->find()) {
                    exception('该邮箱已注册',40001);
                }
            }
            //日期字段置空
            if (empty($data['birthday'])) {
                $data['birthday'] = null;
            }
            $this->isUpdate(false)->allowField(true)->save($data);
            return $this->getData('uid');
        } catch (\Exception $e){
            exception($e->getMessage(),40001);
        }
    }

    /**
     * 编辑用户
     * @param $data
     * @return bool
     */
    public function editData($data)
    {
        try{
            if (empty($data['password'])) {
                unset($data['password']);
            }
            $info = $this->get($data['uid']);
            if (!empty($data['username'])) {
                if ($info['username'] != $data['username']) {
                    if ($this->isUserName($data['username']) === false) {
                        exception('用户名格式错误',40001);
                    }
                    if ($this->where('username', $data['username'])->find()) {
                        exception('该用户已存在！',40001);
                    }
                }
            }
            if (!empty($data['mobile'])) {
                if ($info['mobile'] != $data['mobile']) {
                    if ($this->isMobile($data['mobile']) === false) {
                        exception('手机号格式错误！',40001);
                    }
                    if ($this->where('mobile', $data['mobile'])->find()) {
                        exception('该手机号已注册！',40001);
                    }
                }
            }
            if (!empty($data['email'])) {
                if ($info['email'] != $data['email']) {
                    if ($this->isEmail($data['email']) === false) {
                        exception('email格式错误！',40001);
                    }
                    if ($this->where('email', $data['email'])->find()) {
                        exception('该邮箱已注册！',40001);
                    }
                }
            }
            if ($info['uid'] == 1) $data['status'] = 1; //系统管理员不允许禁用
            if (empty($data['birthday'])) {
                $data['birthday'] = null;
            }
            $this->isUpdate(true)->allowField(true)->save($data);
            return $this->getData('uid');
        } catch (\Exception $e){
            exception($e->getMessage(),40001);
        }
    }

    /**
     * 设置用户状态
     * @param $uid
     * @return bool
     */
    public function setStatus($uid)
    {
        try{
            if ($uid == 1) {
                exception('系统管理员不允许禁用',40001);
            }
            $status = $this->where('uid',$uid)->value('status');
            $status = $status==1?0:1;
            $this->where('uid',$uid)->setField('status',$status);
            return true;
        } catch (\Exception $e){
            exception($e->getMessage(),40001);
        }

    }

    /**
     * 检测用户登录
     * @param $account
     * @param $password
     * @return bool
     */
    public function checkLogin($account, $password, $utype="system")
    {
        try{
            $field = $this->checkUserName($account);
            if (empty($field)) {
                exception('帐户信息有误',40001);
            }
            $user = $this->where($field, $account)->where('utype',$utype)->find();
            if (empty($user)) {
                exception('用户不存在',40001);
            }
            if ($user->getData('password') == md5(sha1($password))) {
                $status = $user->getData('status');
                $uid = $user->getData('uid');
                if ($status == 1) {
                    $loginData = [
                        'last_login_time' => time(),
                        'last_login_ip' => get_client_ip(),
                        'login_times' => $user->getData('login_times') + 1,
                    ];
                    $this->where('uid', $uid)->update($loginData);
                    $token = config('base.login_token');
                    $des = str_encode($uid . $token . $utype);
                    return $des;
                }
                exception('该用户已锁定',40001);
            }
            exception('密码输入错误',40001);
        } catch (\Exception $e){
            exception($e->getMessage(),40001);
        }
    }

    /**
     * 获取用户权限
     * @param $uid
     * @param $utype
     * @return array
     */
    public function getMyRuleList($groupIds, $utype)
    {
        try{
            $ruleList = cache('auth_rule_' . $utype);
            if (empty($ruleList)) {
                $model = new AuthRuleModel();
                $model->updateCache($utype);
                $ruleList = cache('auth_rule_' . $utype);
            }
            $authGroupModel = new AuthGroupModel();
            $rules = $authGroupModel
                ->where('utype',$utype)
                ->where('group_id', 'in', $groupIds)
                ->where('status', 1)
                ->column('rules');
            $rules = array_unique(explode(',',implode(',',$rules))); //去重
            if (empty($rules)) {
                return [];
            }
            if (!in_array('all',$rules)) {
                foreach ($ruleList as $k => $v) {
                    if (in_array($k, explode(',', $rules))) {
                        $myRuleList[$k] = $v;
                    }
                }
            } else {
                $myRuleList = $ruleList;
            }
            $treeRule = TreeUtil::channelLevel($myRuleList, 0, "&nbsp;", 'rule_id', 'rule_pid');
            return $treeRule;
        } catch (\Exception $e){
            exception($e->getMessage(),40001);
        }
    }

    /**
     * @param $account
     * 检测用户名
     */
    public function checkUserName($account)
    {
        if ($this->isUserName($account)) {
            return 'username';
        }
        if ($this->isMobile($account)) {
            return 'mobile';
        }
        if ($this->isEmail($account)) {
            return 'email';
        }
        return '';
    }

    /**
     * 是否用户名
     * @param $username
     * @return bool
     */
    public function isUserName($username)
    {
        $valid = Validate::regex($username, '/^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){3,19}$/');
        if ($valid) {
            return true;
        } else {
            $this->error = '用户名只能为字母和数字且必须以字母开头';
            return false;
        }
    }

    /**
     * 是否手机号
     */
    public function isMobile($mobile)
    {
        $valid = Validate::regex($mobile, '/^1[3456789]{1}\d{9}$/');
        if ($valid) {
            return true;
        } else {
            $this->error = '手机号格式不正确';
            return false;
        }
    }

    /**
     * 是否邮箱
     */
    public function isEmail($email)
    {
        $valid = Validate::is($email, 'email');
        if ($valid) {
            return true;
        } else {
            $this->error = '手机号格式不正确';
            return false;
        }
    }
}